package io.renren.common.aspect;
import io.renren.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author HT
 * @date 2020/2/3 9:04
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    @Pointcut("execution(public * io.renren.modules.*.controller..*.*(..))")
    public void webLogAspect() {
    }

    @Before("webLogAspect()")
    public void doBefore(JoinPoint joinPoint) {

        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            log.info("-------------------------------------------------------------------------------------");
            log.info("Ip : " + request.getRemoteAddr());
            log.info("Url : " + request.getRequestURL().toString());
            log.info("Class_Method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.info("Http_Method : " + request.getMethod());
            log.info("Args : " + Arrays.toString(joinPoint.getArgs()));
            log.info("-------------------------------------------------------------------------------------");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    @AfterReturning(returning = "r", pointcut = "webLogAspect()")
    public void doAfterReturning(R r) {
        log.info("---------------------------------------------------");
        log.info("Response:[" + r + "]");
        log.info("---------------------------------------------------");
    }
}

